import web
import json
import urllib2
import socket

urls=(
	'/monitor/(.*)','get_proportion'
)
app = web.application(urls,globals())

cc = []
cd = []
cm = []
cb = []
k=[0.5,0.1,0.3,0.1]
CN =[]
for i in range(4):
    with open('capacity_%d.txt' %i, 'r') as f:
        cc.append(float(f.readline()))
        cd.append(float(f.readline()))
        cm.append(float(f.readline()))
        cb.append(float(f.readline()))
        CN.append(k[0]*cc[i]+k[1]*cd[i]+k[2]*cm[i]+k[3]*cb[i])
pro_lats=[0.25, 0.25, 0.25, 0.25]
#with open('pro_last.txt','r') as f:
#    pro_lats=f.readlines()


class get_proportion:
    def GET(self,nums):
        url = "http://10.108.166.75:8088/sparkPlatform/monitor"
        response = urllib2.urlopen(url, timeout=5)
        nums = int(nums)

        try:
            response = urllib2.urlopen(url, timeout=5)
        except urllib2.URLError, e:
            return pro_lats

        except socket.timeout, e:
            return pro_lats

        res = response.read()
        print res
        if res == '':
            return pro_lats

        #response = urllib2.urlopen(url)
        jsons = json.loads(res)
        lc=[]
        ld=[]
        lm=[]
        lb=[]
        LN=[]
        r=[0.5, 0.2, 0.2, 0.1]
        PN=[]
        sum=0
        for i in range(len(jsons)):
            lc.append(float(jsons[i]['cpuRate']))
            ld.append(float(str(jsons[i]['IORate'])[:-2]))
            lm.append(float(jsons[i]['memRate']))
            lb.append(float(str(jsons[i]['NetInfo'])[:-2]))
            LN.append(r[0] * lc[i] + r[1] * ld[i] + r[2] * lm[i] + r[3] * lb[i])
            PN.append(LN[i] / CN[i])
            sum+=1-PN[i]
        WN=[]
        for p in PN:
            WN.append((1-p)/sum)
        for i in range(len(WN)):
            pro_lats[i]+=WN[i]
            pro_lats[i]/=2;

        return str(pro_lats)



if __name__ == '__main__':
    app.run()